package com.lgl.mes.daily.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lgl.mes.common.util.DateUtil;
import com.lgl.mes.common.util.log.SysLog;
import com.lgl.mes.daily.entity.SpDailyPlan;
import com.lgl.mes.globalId.entity.SpGlobalId;
import com.lgl.mes.globalId.service.ISpGlobalIdService;
import com.lgl.mes.order.entity.SpOrder;
import com.lgl.mes.order.service.ISpOrderService;
import com.lgl.mes.product.entity.SpProduct;
import com.lgl.mes.basedata.entity.SpTableManager;

import com.lgl.mes.daily.request.spDailyPlanReq;
import com.lgl.mes.product.request.spProductReq;
import com.lgl.mes.common.Result;
import com.lgl.mes.common.util.DateUtil;

import com.lgl.mes.daily.service.ISpDailyPlanService;

import com.lgl.mes.product.service.ISpProductService;
import com.lgl.mes.workReport.entity.SpWorkReport;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import com.lgl.mes.common.BaseController;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author dreamer,75039960@qq.com
 * @since 2022-06-27
 */
@Controller
@RequestMapping("/daily/plan")
public class SpDailyPlanController extends BaseController {

    @Autowired
    private ISpDailyPlanService iSpDailyPlanService;

    @Autowired
    private ISpOrderService iSpOrderService;

    @Autowired
    private ISpGlobalIdService iSpGlobalIdService;

    @Autowired
    private ISpProductService iSpProductService;


    @ApiOperation("每日计划列表界面UI")
    @ApiImplicitParams({@ApiImplicitParam(name = "model", value = "模型", defaultValue = "模型")})
    @GetMapping("/list-ui")
    public String listUI(Model model) {

        return "daily/list";
    }


    /**
     * 每日计划管理修改界面
     *
     * @param record 平台表对象
     * @return 更改界面
     */
    @ApiOperation("每日计划管理修改界面")
    @GetMapping("/add-or-update-ui")
    public String addOrUpdateUI(Model model, SpTableManager record) {
        if (StringUtils.isNotEmpty(record.getId())) {
            SpDailyPlan spDailyPlan = iSpDailyPlanService.getById(record.getId());
            model.addAttribute("result", spDailyPlan);
        }
        return "daily/addOrUpdate";
    }

    /**
     * 每日计划管理界面分页查询
     *
     * @param req 请求参数
     * @return Result 执行结果
     */
    @ApiOperation("每日计划管理界面分页查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "req", value = "请求参数", defaultValue = "请求参数")})
    @PostMapping("/page")
    @ResponseBody
    public Result page( spDailyPlanReq  req) {   //  //spDailyPlanReq
        QueryWrapper<SpDailyPlan> queryWrapper =new QueryWrapper();
        if (StringUtils.isNotEmpty(req.getOrderCode()))
        {
            queryWrapper.like("order_code",req.getOrderCode());
        }


        if (req.getCreateTime1() !=null && !req.getCreateTime1().isEmpty())
        {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate= LocalDate.parse(req.getCreateTime1(), formatter);
            //queryWrapper.ge("createTime",ld);
            queryWrapper.apply("UNIX_TIMESTAMP(create_time) >= UNIX_TIMESTAMP('" + localDate + "')");
        }


        if (req.getCreateTime2() !=null && !req.getCreateTime2().isEmpty())
        {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate= LocalDate.parse(req.getCreateTime2(), formatter);
            queryWrapper.apply("UNIX_TIMESTAMP(create_time) <= UNIX_TIMESTAMP('" + localDate + "')");
        }

        IPage result = iSpDailyPlanService.page(req,queryWrapper);



        return Result.success(result);
    }



    @SysLog("修改，新增日计划")
    @ApiOperation("每日计划管理修改、新增")
    @PostMapping("/add-or-update")
    @ResponseBody
    public Result addOrUpdate(SpDailyPlan   record)  throws Exception {
        if(record.getPlanDate()!=null ) {
            //record.setPlanDate(DateUtil.GetShortStampString(record.getPlanDate().toString()));
            record.setPlanDate(DateUtil.GetStampString(record.getPlanDate().toString()));
        }

        if(record.getMorningStart()!=null )
            record.setMorningStart( DateUtil.GetStampString(record.getMorningStart().toString()));
        if(record.getMorningEnd()!=null )
            record.setMorningEnd( DateUtil.GetStampString(record.getMorningEnd().toString()));
        if(record.getMorningStart1()!=null )
            record.setMorningStart1( DateUtil.GetStampString(record.getMorningStart1().toString()));
        if(record.getMorningEnd1()!=null )
            record.setMorningEnd1( DateUtil.GetStampString(record.getMorningEnd1().toString()));



        if(record.getAfternoonStart()!=null )
            record.setAfternoonStart( DateUtil.GetStampString(record.getAfternoonStart().toString()));
        if(record.getAfternoonEnd()!=null )
            record.setAfternoonEnd( DateUtil.GetStampString(record.getAfternoonEnd().toString()));
        if(record.getAfternoonStart1()!=null )
            record.setAfternoonStart1( DateUtil.GetStampString(record.getAfternoonStart1().toString()));
        if(record.getAfternoonEnd1()!=null )
            record.setAfternoonEnd1( DateUtil.GetStampString(record.getAfternoonEnd1().toString()));

        if(record.getEveningStart()!=null )
            record.setEveningStart( DateUtil.GetStampString(record.getEveningStart().toString()));
        if(record.getEveningEnd()!=null )
            record.setEveningEnd( DateUtil.GetStampString(record.getEveningEnd().toString()));
        if(record.getEveningStart1()!=null )
            record.setEveningStart1( DateUtil.GetStampString(record.getEveningStart1().toString()));
        if(record.getEveningEnd1()!=null )
            record.setEveningEnd1( DateUtil.GetStampString(record.getEveningEnd1().toString()));


        iSpDailyPlanService.saveOrUpdate(record);

        return Result.success();
    }


    /**
     * 删除计划信息
     * 删除当日计划信息,如果是删除订单的最后一条信息，则删除订单计划
     *
     * @param req 请求参数
     * @return Result 执行结果
     */
    @SysLog("删除日计划")
    @ApiOperation("删除当日计划信息,如果是删除订单的最后一条信息，则删除订单计划")
    @ApiImplicitParams({@ApiImplicitParam(name = "req", value = "产品实体", defaultValue = "产品实体")})
    @PostMapping("/delete")
    @ResponseBody
    public Result deleteByTableNameId(SpDailyPlan req) throws Exception {

         if(req.getId()==null)
         {
             return  Result.failure("没有订单ID");
         }
        //SpDailyPlan spDailyPlan =iSpDailyPlanService.getById(req.getId());
         //String orderCode = spDailyPlan.getOrderCode();
        iSpDailyPlanService.removeById(req.getId());

        /////////////////////如果是删除订单的最后一条信息，则删除订单计划////
/*
        QueryWrapper<SpDailyPlan> queryWrapperDaily = new QueryWrapper();
        queryWrapperDaily.eq("order_code", orderCode);
        List<SpDailyPlan> list =iSpDailyPlanService.list(queryWrapperDaily);
        if(list ==null  || list.size()==0){
            QueryWrapper<SpOrder> queryWrapper = new QueryWrapper();
            queryWrapper.eq("order_code", orderCode);
            SpOrder spOrder = iSpOrderService.getOne(queryWrapper);
            iSpOrderService.removeById(spOrder.getId());
        }
*/

        return Result.success();
    }


    @ApiOperation("批量删除计划信息")
    @ApiImplicitParams({@ApiImplicitParam(name = "ids", value = "play ids", defaultValue = "plan ids")})
    @PostMapping("/batchDelete")
    @ResponseBody
    public Result batchDelete( String  ids) throws Exception {

        String[] tempList = ids.split(",");
        for (String id  :  tempList)
        {
            iSpDailyPlanService.removeById(id);
        }


        return Result.success();
    }



    @SysLog("设置当前日计划")
    @PostMapping("/setCurrentOrder")
    @ResponseBody
    public Result setCurrentOrder(String dailyPlanId) {
        //String orderCode = para.getOrderCode();//jsonObj.getString("orderCode");

        if ( dailyPlanId ==null || dailyPlanId.isEmpty() ){

            return Result.failure("计划id不能为空");
        }

        try{

            SpDailyPlan  dp =iSpDailyPlanService.getById(dailyPlanId);


            java.util.Date date = new Date();
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
            String dateString = formatter.format(date);
            if(!dp.getPlanDate().substring(0,10).equals(dateString))
            {
                return Result.failure("目标日期不匹配!");
            }


            QueryWrapper<SpGlobalId> queryWrapper = new QueryWrapper();
            queryWrapper.like("line", dp.getLineId());
            List<SpGlobalId> list = iSpGlobalIdService.list(queryWrapper);;



            SpGlobalId spGlobalId;
            if(list.size()==0)
            {
                spGlobalId = new SpGlobalId();
                spGlobalId.setOrderCode(dp.getOrderCode());
                spGlobalId.setLine(dp.getLineId());
            }
            else
            {
                spGlobalId = iSpGlobalIdService.getById(list.get(0).getId()); //order_code其实也是唯一的
                spGlobalId.setOrderCode(dp.getOrderCode());

            }

            iSpGlobalIdService.saveOrUpdate(spGlobalId);
            return Result.success(null,"设置成功");
        }
        catch (Exception e) {
            return Result.failure("数据异常 ，"+e.getMessage());
        }

    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json")
    public Result getList() throws Exception {


        List<SpDailyPlan> list = iSpDailyPlanService.list();

        return Result.success(list);
    }

    // 需要放到专门的API 目录下面
    /*@GetMapping("/GetCurrentOrderCode")
    @ResponseBody
    public Result GetCurrentOrderCode() {
        String orderCode = iSpProductService.GetCurrentOrderCode();

        if(orderCode ==null)
        {
            return Result.failure("没有设置当前订单编码");
        }
        return Result.success(orderCode, "返回当前订单编码");
    }*/
}
